from flask_babel import _
import pandas as pd
from flask import request
from flask_login import current_user
from flask_restful import Resource, marshal_with, reqparse  # type: ignore
from controllers.console import api
from controllers.errors.robots_error import HTTPRobotImportError, HTTPRobotNotFoundError
from core.roles.role_check import check_perms
from libs.helper import extract_remote_ip
from libs.login import login_required
from fields.robot.robots_fields_def import robot_list_fields,robot_fields,robot_import_fields
from models.robot.robots import AgentType
from services.errors.robots import RobotNotExistError
from services.robot.robots_service import RobotsService


class RobotManangeApi(Resource):
    @login_required
    @check_perms(perms=['robots:list'])
    @marshal_with(robot_list_fields)
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', type=str, required=False, location='args')
        parser.add_argument('hardware_version', type=str,
                            required=False, location='args')
        parser.add_argument('fireware_version', type=str,
                            required=False, location='args')
        parser.add_argument('is_active', type=bool,
                            required=False, default=None, location='args')
        parser.add_argument('fun_domain_id', type=str,
                            required=False, location='args')
        parser.add_argument('agent_type', type=str, choices=[
                            "agent", "flow_pot", None, ''], required=False, location='args')
        parser.add_argument('page', type=int, required=False,
                            default=-1, location='args')
        parser.add_argument('page_size', type=int,
                            required=False, default=-1, location='args')
        args = parser.parse_args()
        return RobotsService.get_robot_list(current_user.current_tenant_id, args)

    @login_required
    @check_perms(perms=['robots:new'])
    @marshal_with(robot_fields)
    def post(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument('id', type=str, required=True, location='json')
        # argparser.add_argument('hardware_version',type=str,required=True,location='json')
        # argparser.add_argument('fireware_version',type=str,required=True,location='json')
        argparser.add_argument('agent_type', type=str,
                               required=True, location='json')
        argparser.add_argument('fun_domain_id', type=str,
                               required=True, location='json')
        argparser.add_argument('extra_funcs', type=str,action='append',
                               required=False, location='json')
        argparser.add_argument('extra_timbres', type=str,action='append',
                               required=False, location='json')
        argparser.add_argument('extra_emoji_packs',
                               type=str,action='append', required=False, location='json')
        argparser.add_argument('chat_language',type=str,required=False,location='json')
        args = argparser.parse_args()
        try:
            RobotsService.create_robot(
                current_user, extract_remote_ip(request), args)
        except RobotNotExistError as e:
            raise HTTPRobotNotFoundError(e.robot_id)
        except Exception as e:
            raise

    @login_required
    @check_perms(perms=['robots:update'])
    @marshal_with(robot_fields)
    def put(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument('id', type=str, required=True, location='json')
        # argparser.add_argument('hardware_version',type=str,required=True,location='json')
        # argparser.add_argument('fireware_version',type=str,required=True,location='json')
        argparser.add_argument('agent_type', type=str,
                               required=True, location='json')
        argparser.add_argument('fun_domain_id', type=str,
                               required=True, location='json')
        argparser.add_argument('extra_funcs', type=str,
                               required=False, location='json')
        argparser.add_argument('extra_timbres', type=str,
                               required=False, location='json')
        argparser.add_argument('extra_emoji_packs',
                               type=str, required=False, location='json')
        argparser.add_argument('account_id',type=str,required=False,location='json')
        argparser.add_argument('chat_language',type=str,required=False,location='json')
        argparser.add_argument('user_name',type=str,required=False,location='json')
        argparser.add_argument('postal_code',type=str,required=False,location='json')
        
        args = argparser.parse_args()
        try:
            RobotsService.update_robot(
                current_user, extract_remote_ip(request), args)
        except RobotNotExistError as e:
            raise HTTPRobotNotFoundError(e.robot_id)
        except Exception as e:
            raise

    @login_required
    @check_perms(perms=['robots:del'])
    def delete(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument('id', type=str, required=True, location='json')
        args = argparser.parse_args()
        try:
            RobotsService.delete_robot(
                current_user, args.id, extract_remote_ip(request))
        except RobotNotExistError as e:
            raise HTTPRobotNotFoundError(e.robot_id)
        except Exception as e:
            raise


class RobotImportApi(Resource):
    @login_required
    @check_perms(perms=['robots:new'])
    @marshal_with(robot_import_fields)
    def post(self):
        form_data = request.form.to_dict()
        agent_type = AgentType(form_data.get("agent_type")) if form_data.get("agent_type",None) else None
        fun_domain_id = form_data.get("fun_domain_id", None)
        character_id = form_data.get("character_id", None)
        timbre_id = form_data.get("timber_id", None)
        emoji_pack_id = form_data.get("emoji_pack_id", None)
        extra_funcs = form_data.get("extra_funcs", {})
        extra_timbres = form_data.get("extra_timbres", {})
        extra_emoji_packs = form_data.get("extra_emoji_packs", {})
        chat_language = form_data.get("chat_language", "zh")

        if "file" not in request.files:
            raise HTTPRobotImportError(_("Please select a file to import."))
        file = request.files["file"]
        if file.filename == "":
            raise HTTPRobotImportError(_("Please select a file to import."))

        if file and file.filename and file.filename.endswith(".xlsx"):
            df = pd.read_excel(file)
            data,messages= RobotsService.import_robots(
                current_user, df,agent_type, fun_domain_id, character_id, timbre_id, emoji_pack_id, extra_funcs, extra_timbres, extra_emoji_packs,chat_language, extract_remote_ip(request)
            )
            lena = len(data) if data else 0
            return {"data":data,"messages":messages,"len":lena}
        else:
            return {"messages": ["Only .xlsx files are allowed"]}, 400
        
api.add_resource(RobotImportApi, '/robots/import')
api.add_resource(RobotManangeApi, '/robots/manage')
